<template>
  <div class="heartPaper-page"  >
    <GhNavBar title="用户小纸条"  />
    <!-- 骨架屏 -->
    <van-skeleton title :row="3" v-if="rows.length===0" />
    <van-skeleton title :row="5" v-if="rows.length===0" />
    <van-skeleton title :row="9" v-if="rows.length===0" />
    <div class="waterfall-flow">
      <div class="rows" v-for="(item, index) in rows" :key="index">
        <div class="card" v-for="(cardItem, cardIndex) in item" :key="cardIndex" @click="openCardItem(cardItem)">
          <img :src="cardItem.image" alt="image" class="image">
          <div class="content">
            <h3 class="title">{{ cardItem.title }}</h3>
            <div class="bottom">
              <p class="author">{{ cardItem.author }}</p>
              <p class="created">{{ cardItem.created_at }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
     <van-button class="fixed-box" type="primary" @click="showPublish = true">
      <van-icon name="plus" size="18" />
    </van-button>
    <!-- 弹出发布纸条 -->
    <div class="publish-box">
      <van-popup class="popup"   v-model:show="showPublish" @close="close" round closeable position="top">
        <h1>发布小纸条</h1>
        <van-field v-model="title" label="标题" maxlength="16" placeholder="限制字数16" required label-width="40px" autocomplete="off"></van-field>
         <!-- 显示上传图片 -->
         <div class="avatar" >
          <van-uploader v-model="image" required  @delete="deleteClzp"  @oversize="onOversize" :before-read="beforeRead" :after-read="clzpAfterRead"  accept="image/*"  :preview-image="true" :max-count="1" :max-size="5 * 1024 * 1024"   >
          </van-uploader> 
          <h3>上传图片</h3>
        </div>
        <van-field
      
        v-model="content"
        label="内容"
        required
        label-width="30px"
        rows="5"
        class="custom-field"
        autosize
        maxlength="80"
        type="textarea"
        show-word-limit
        placeholder="一句话释放自己"
    />
       
    <van-button native-type="submit" @click="publishContent" :loading="isRegistering" :disabled="isRegistering" block round type="primary">
      发布
    </van-button>
      </van-popup>
    
    </div>
      
    </div>
</template>

<script setup>
import GhNavBar from '@/components/gh-nav-bar.vue'
import { ref, onMounted, onBeforeUnmount } from 'vue';
import {publishPaper,getPublishAllInfo } from '@/services/others'
import { Toast, Dialog } from 'vant'
import 'vant/es/toast/style'
//点击打开每个纸条
const openCardItem=(cardItem)=>{
  // console.log(cardItem.title)
  Dialog.alert({
  title: cardItem.title,
  message: cardItem.content,
})
}


//定义发布纸条数据
const title=ref('')
const content=ref('')
const image=ref()
const uploadfile=ref()
const account=ref('')
const username=ref('')
const userInfo=JSON.parse(localStorage.getItem('gh-user')).user.userData
account.value=userInfo.account
username.value=userInfo.username

//校验上传图片大小
const onOversize = (file) => {
 Toast("文件大小不能超过5MB");
};
//校验图片的格式
const beforeRead = (file) => {
  if (!/(jpg|jpeg|png|JPG|PNG)/i.test(file.type)) {
    Toast("请上传正确格式的图片");
    return false;
  }
  return true;
};
//照片上传事件方法
const clzpAfterRead = (file) => {
  // 上传状态提示开启
  file.status = "uploading";
  file.message = "上传中...";
  // console.log(file)
  uploadfile.value=file.content
  file.status = "done";
  Toast('添加图片成功')
};
//照片删除事件方法
const deleteClzp = () => {
  // image.value=''
};
//关闭发布弹出框
const close=()=>{
  showPublish.value=false
  title.value=''
   image.value=[]
   content.value=''
}

// 点击发布的展开框
const showPublish=ref(false)
// 粘性布局
const container=ref(null)
//存放后端传过来的按时间排序的数据
const items = ref('');
const rows = ref([]);

const fetchData = async () => {
  const response = await getPublishAllInfo();
  const rows = response.data;
  rows.forEach(row => {
    const { totalChunks, base64Chunks } = row.image;
    let imageData;
    for (let i = 0; i < base64Chunks.length; i++) {
      const base64Data = base64Chunks.join('');
      imageData = `data:image/jpeg;base64,${base64Data}`;
      row.image = imageData;
    }
  });
  console.log(rows)
  items.value = rows;
  splitItemsIntoRows();
  window.addEventListener('resize', splitItemsIntoRows);
};

onMounted(fetchData);

const splitItemsIntoRows = () => {
  const itemsPerRow = 2;
  //计算需要多少行来展示数据
  const numRows = Math.ceil(items.value.length / itemsPerRow);
  // console.log(...items.value)
  let sortedItems = [...items.value].sort(
    (a, b) => new Date(a.createdAt) - new Date(b.createdAt)
  );
  //将排序后的数组分为多个子数组
  rows.value = Array.from({ length: numRows }, (_, index) =>
    sortedItems.slice(index * itemsPerRow, (index + 1) * itemsPerRow)
  );
  // console.log(rows)
};

// onMounted(async () => {
//   const response= await getPublishAllInfo()
//   // console.log(response)
//   const rows=response.data
//   rows.forEach(row => {
//   const{totalChunks, base64Chunks}=row.image
//   // console.log(totalChunks, base64Chunks)
//   let imageData
//   for(let i = 0; i < base64Chunks.length; i++) {
//   // 合并分块 Base64 数据
//  const base64Data = base64Chunks.join('');
//   imageData = `data:image/jpeg;base64,${base64Data}`;
//   // console.log(imageData)
//   row.image=imageData
//   }
// });
// console.log(rows)
// items.value=rows

//   splitItemsIntoRows();
//   window.addEventListener('resize', splitItemsIntoRows);
// });

onBeforeUnmount(() => {
  window.removeEventListener('resize', splitItemsIntoRows);
});

const isRegistering = ref(false);
//发表功能
const publishContent=()=>{
  // 判断标题、内容和图片是否填写或上传
  if (title.value.trim() === '') {
    Toast('请填写标题');
    return;
  }  
  if (content.value.trim() === '') {
    Toast('请填写内容');
    return;
  }
  if (!image.value||image.value.length === 0) {
    Toast('请上传图片');
    return;
  }
  isRegistering.value = true;
  //  console.log(uploadfile.value)
  const formData=new FormData();
  formData.append('title', title.value);
  formData.append('uploadfile',uploadfile.value);
  formData.append('content', content.value);
  formData.append('account',account.value)
  formData.append('username',username.value)
  setTimeout(async()=>{
   const res=await publishPaper(formData).then((response)=>{
      return response
    }).catch((error)=>{
     return error
    })
   console.log(res)
   Toast.success('发布成功！')
   title.value=''
   image.value=[]
   content.value=''
   showPublish.value=false
   fetchData()
   isRegistering.value=false
  },1000)
  
   
   console.log('发表成功')
}

</script>

<style lang="scss" scoped>
.heartPaper-page{
   .waterfall-flow{
    background-color: #f1f1f1;
   margin-top: 40px;
   display: grid;
   grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
   gap: 5px;
   .rows {
      display: flex;
      height: 250px;
      gap: 5px;
      .card {
        flex: 1;
        /* background-color: #f1f1f1; */
        border-radius: 12px;
        background-color: #fff;
        padding: 6px;
        height: 100%;
        position: relative;
           .image {
            display: block;
            width: 100%;
            height: 160px;
            max-height: 200px;
              }
            .content{
              width: 100%;
              height: 80px;
              position: absolute;
              bottom: 0;
              left: 0;
              box-sizing: border-box;
              margin-top: 5px;
              padding: 8px;
              font-family: '黑体';
              .title {
                 font-size: 14px;
                 font-weight: bold;
                 overflow: hidden;
                 color: var(--gh-text1);
                 display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                text-overflow: ellipsis;
                }
              .bottom{
                padding-top: 5px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                .author {
                  overflow: hidden;
                  flex: 1;
                  font-size: 10px;
                  color: var(--gh-text3);
                }
                .created {
                 padding-top: 5px;
                 font-size: 12px;
                 color: #999;
                 }

              }
             }

        }
    }
  }
  .fixed-box{
    position:fixed;
    z-index:999px;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%);
    border-radius: 10px;
  }
  .publish-box{
    display: flex;
    text-align: center;
    justify-content: center;
    flex-direction: column;
    .van-popup{
     .van-field{
           font-family: '黑体';
           font-size: 16px;
      }
     h1{
         margin-bottom: 5px;
         margin-top: 10px;
         font-size: 17px;
         font-weight: 600;
         font-family: '宋体';
     }
     .avatar{
       margin: 15px 0 2px;
      }
     .van-button{
           width: 80%;
           left: 50%;
           margin-top: 10px;
           transform: translate(-50%);
           height: 40px;
           margin-bottom: 20px;
           font-size: 16px;
         }
   }
  }
  
}
</style>
